package com.cloud.layuimini.service;

import com.cloud.layuimini.dao.MenuDao;
import com.cloud.layuimini.dto.MenuVo;
import com.cloud.layuimini.entity.MenuEntity;
import com.cloud.layuimini.util.TreeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
@Transactional(readOnly = true,rollbackFor = Exception.class)
public class MenuServiceImpl implements MenuService {

    @Autowired
    private MenuDao menuDao;

    @Override
    public void jpaDemo() {
        //新增
       // menuDao.save();
    }

    @Override
    public Map<String, Object> menu() {
        Map<String, Object> map = new HashMap<>(16);
        List<MenuEntity> menuList = menuDao.findAll();
        List<MenuVo> menuInfo = new ArrayList<>();
        for (MenuEntity e : menuList) {
            MenuVo menuVO = new MenuVo();
            menuVO.setId(e.getId());
//            menuVO.setPid(e.getPid());
//            menuVO.setHref(e.getHref());
//            menuVO.setTitle(e.getTitle());
//            menuVO.setIcon(e.getIcon());
//            menuVO.setTarget(e.getTarget());
            menuInfo.add(menuVO);
        }
        map.put("menuInfo", TreeUtil.toTree(menuInfo, 0L));
        map.put("homeInfo", "{title: '首页',href: '/ruge-web-admin/page/welcome.html'}}");
        map.put("logoInfo", "{title: 'RUGE ADMIN',image: 'images/logo.png'}");
        return map;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @Modifying
    public void save(MenuEntity menuEntity) throws Exception {
        menuDao.save(menuEntity);
    }

    @Override
    public List<MenuEntity> findAll() throws Exception {
        return menuDao.findAll();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @Modifying
    public void update(MenuEntity menuEntity) throws Exception {
        menuDao.saveAndFlush(menuEntity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @Modifying
    public void delete(Long id) throws Exception {
        menuDao.deleteById(id);
    }
}
